const Koa = require('koa');
const router = require('koa-router')();
const static = require('koa-static');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const render = require('koa-art-template');
const path = require('path');
const { logger, accessLogger } = require('./modules/logger');

const admin = require('./routes/admin');
const apis = require('./routes/apis');
const web = require('./routes/web');

const app = new Koa();

// access logger
app.use(accessLogger());

// body parser
app.use(bodyParser());

// static server
app.use(static(__dirname + '/public'));

// session
app.keys = ['some secret hurr'];
const CONFIG = {
    key: 'koa:sess',
    maxAge: 30*60*1000,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: true,
    renew: false,
};
app.use(session(CONFIG, app));

// art template
render(app, {
    root: path.join(__dirname, 'views'),
    extname: '.html',
    debug: process.env.NODE_ENV !== 'production'
});

// start routes
router.use('/admin', admin);
router.use('/apis', apis);
router.use(web);

app.use(router.routes());
app.use(router.allowedMethods());

// global error
app.on('error', err => {
    logger.error(err);
});

app.listen(3000, () => {
    console.log('Starting at port 3000 ...');
});